package com.cos.lession67.web.servlet;

import com.cos.lession67.common.Const;

import javax.annotation.Resources;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * @author: COS
 * @time: 2022/9/21 17:31
 * @description:
 */
public class BaseServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            //1 获取method
            String method = req.getParameter("method");
            //2 反射
            Class aClass = this.getClass();
            //3 找方法
            Method method1 = aClass.getMethod(method, HttpServletRequest.class, HttpServletResponse.class);
            //4 调用
            String result = (String) method1.invoke(this, req, resp);
            //5 判断什么操作
            if (result != null) {
                if (result.contains(Const.FORWARD)) {
                    req.getRequestDispatcher(result.replace(Const.FORWARD, "")).forward(req, resp);
                } else if (result.contains(Const.REDIRECT)) {
                    resp.sendRedirect(result.replace(Const.REDIRECT, ""));
                } else {
                    resp.getWriter().println(result);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            resp.sendRedirect(req.getContextPath()+"/error.jsp");
        }
    }
}
